#include "head.h"

void *threadMain(void *p) {
    pool_t *pool = (pool_t *)p;
    MYSQL mysql;
    printf("进入线程\n");
    while (1)
    {
        pthread_mutex_lock(&pool->lock);
        // 等待队列中有任务
        while (pool->queue.size == 0 && pool->exitFlag == 0) {
            pthread_cond_wait(&pool->cond, &pool->lock);
        }
        // 退出线程
        if (pool->exitFlag == 1) {
            // 关闭数据库连接
            mysql_close(&mysql);

            pthread_mutex_unlock(&pool->lock);
            pthread_exit(NULL);
        }
        // 取出任务
        int net_fd = pool->queue.head->net_fd;
        request_t *request = pool->queue.head->request;
        deQueue(&pool->queue);

        // 初始化数据库
        mysql_init(&mysql);
        // 连接数据库   
        char mysql_user[60] = {0};
        load_config("mysql_user", mysql_user);
        char mysql_password[60] = {0};
        load_config("mysql_password", mysql_password);
        char mysql_db[60] = {0};
        load_config("mysql_db", mysql_db);

        mysql_real_connect(&mysql, "localhost", mysql_user, mysql_password, mysql_db, 0, NULL, 0);
        // printf("connect: %s \n", mysql_error(&mysql));

        pthread_mutex_unlock(&pool->lock);

        // 处理任务
        // printf("begin serve\n");
        LOG(INFO, request->user_name, "threadMain", "begin server");
        if(request->flag == PUTS)
        {
            net_puts(request, net_fd, &mysql);
        }
        else if(request->flag == GETS)
        {
            net_gets(request, net_fd, &mysql);
        }
        // printf("close serve\n");
        LOG(INFO, request->user_name, "threadMain", "close server");
    }

    return NULL;
}
